//
//  KeyChainViewController.swift
//  funcode
//
//  Created by Wan Jiading on 2017/7/13.
//  Copyright © 2017年 WanJiading. All rights reserved.
//

import UIKit
import KeychainAccess

class KeyChainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

		
		let userPwd1 = getUserPwd("roshan", "roshanpwd")
		addUser(userPwd1)
		
		let userPwd2 = getUserPwd("wahaha", "wahahaPwd")
		addUser(userPwd2)
		
		let list = getPwdList()
		list?.forEach({ (item) in
			DebugLog("key:\(item.telephone)   value:\(item.password)")
		})
    }
	
	func getUserPwd(_ tel: String, _ pwd: String) -> UserPwdModel {
		let userPwd = UserPwdModel()
		userPwd.telephone = tel
		userPwd.password = pwd
		
		return userPwd
	}
	
	
	
	/// Key:手机号  Value:密码
	func getPwdList() -> [UserPwdModel]? {
		let keychain = getKeychain()
		do {
			if let data = try keychain.getData("UserPwdList") {
				do {
					let userPwdList = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.init(rawValue: 0))
					let list = userPwdList as? [UserPwdModel]
					return list
				} catch let error {
					DebugLog(error)
				}
			}
		} catch let error {
			DebugLog(error)
		}
		
		return nil
	}
	
	func addUser(_ userPwd: UserPwdModel) {
		var userPwdList = [UserPwdModel]()
		if let oldUserPwdList = getPwdList() {
			userPwdList = oldUserPwdList
		}
		userPwdList.append(userPwd)
		
		do {
			let json = try JSONSerialization.data(withJSONObject: userPwdList, options: .prettyPrinted)
			do {
				let keychain = getKeychain()
				try keychain.set(json, key: "UserPwdList")
			} catch let error {
				DebugLog(error)
			}
		} catch let error {
			DebugLog(error)
		}
	}

	func getKeychain() -> Keychain {
		return Keychain(server: "ivydad", protocolType: .https)
	}
}
